let models = require('../models')
const {deepCloneSimple} = require("../utils/putlic/index")
const sequelize = require("../models/index.js").sequelize
const {
    SuccessModel,
    ErrorModel
} = require('../utils/resModel')
const {parseToken} = require('../utils/cryp')
const rootUser = ['admin', 'miuseik']

const allList = async (ctx) => {
    let list = await models.bones.findAll({
        order: [['sort', 'ASC']] // 按 sort_order 字段升序排序
    });
    for (const data of list) {
        const boneId = data.id;
        const options = await models.bones_option.findAll({
            where: {
                pid: boneId
            }
        });
        const option = {};
        for (const opt of options) {
            const dataValues = opt.dataValues || {};
            option[dataValues.key] = dataValues;
        }
        data.dataValues.option = option;

        // 查询 bones_positions 表的数据
        const positions = await models.bones_position.findAll({
            where: {
                pid: boneId
            }
        });
        const position = {};
        for (const pos of positions) {
            const dataValues = pos.dataValues || {};
            position[dataValues.key] = dataValues.value;
        }
        data.dataValues.position = position;

        // 查询 bones_rotates 表的数据
        const rotates = await models.bones_rotate.findAll({
            where: {
                pid: boneId
            }
        });
        const rotate = {};
        for (const rot of rotates) {
            const dataValues = rot.dataValues || {};
            rotate[dataValues.key] = dataValues.value;
        }
        data.dataValues.rotate = rotate;
    }
    return list;
};

const newData = async (param) => {
    const {userData} = parseToken(ctx)
    if(!rootUser.includes(userData.username)){
        return '朋友,不可以!';
    }else {
        try {
            return await sequelize.transaction(async () => {
                delete param.id
                // 提取 position 和 rotate 数据
                const {position, rotate, option} = param;
                let data = await models.bones.create(param)
                // 处理 position 数据
                for (let key in position) {
                    let positionItem = {
                        key,
                        value: position[key],
                        pid: data.id
                    };
                    await models.bones_position.create(positionItem);
                }
                // 处理 rotate 数据
                for (let key in rotate) {
                    let rotateItem = {
                        key,
                        value: rotate[key],
                        pid: data.id
                    };
                    await models.bones_rotate.create(rotateItem);
                }

                for (let key in option) {
                    let optionItem = option[key]
                    optionItem.key = key
                    optionItem.pid = data.id
                    await models.bones_option.create(optionItem);
                }
                return data.dataValues
            });
        } catch (error) {
            ctx.body = new ErrorModel(error);
        }
    }
}
const destroy = async (ctx, query) => {
    const {userData} = parseToken(ctx)
    if(!rootUser.includes(userData.username)){
        return '朋友,不可以!';
    }else {
        try {
            return await sequelize.transaction(async (t) => {
                // 根据传入的 id 查找要删除的 bones 记录
                const bone = await models.bones.findByPk(query.id, {transaction: t});
                if (!bone) {
                    throw new Error('未找到对应的 bones 记录');
                }
                const boneId = bone.id;
                // 删除关联的 bones_position 记录
                await models.bones_position.destroy({
                    where: {
                        pid: boneId
                    },
                    transaction: t
                });
                // 删除关联的 bones_rotate 记录
                await models.bones_rotate.destroy({
                    where: {
                        pid: boneId
                    },
                    transaction: t
                });
                // 删除关联的 bones_option 记录
                await models.bones_option.destroy({
                    where: {
                        pid: boneId
                    },
                    transaction: t
                });
                // 删除 bones 记录
                await bone.destroy({transaction: t});
                return '删除成功';
            });
        } catch (error) {
            ctx.body = new ErrorModel(error);
        }
    }
}

const revise = async (ctx, query) => {
    const {userData} = parseToken(ctx)
    console.log('userData.username', userData.username)
    if(!rootUser.includes(userData.username)){
        return '朋友,不可以!';
    }else {
        try {
            return await sequelize.transaction(async (t) => {
                // 查找要修改的 bones 记录
                let dataOV = await models.bones.findByPk(query.id, {transaction: t});
                if (!dataOV) {
                    throw new Error('未找到对应的 bones 记录');
                }
                // 提取 position、rotate 和 option 数据
                const { position, rotate, option, ...restQuery } = query;
                // 处理 position 数据
                for (let key in position) {
                    const newValue = position[key];
                    let positionRecord = await models.bones_position.findOne({
                        where: {
                            pid: query.id,
                            key: key
                        },
                        transaction: t
                    });
                    await positionRecord.update({value: newValue}, {transaction: t});
                }
                // 处理 rotate 数据
                for (let key in rotate) {
                    const newValue = rotate[key];
                    let rotateRecord = await models.bones_rotate.findOne({
                        where: {
                            pid: query.id,
                            key: key
                        },
                        transaction: t
                    });
                    await rotateRecord.update({value: newValue}, {transaction: t});
                }
                // 处理 option 数据
                for (let key in option) {
                    const newValue = option[key];
                    let optionRecord = await models.bones_option.findOne({
                        where: {
                            pid: query.id,
                            key: key
                        },
                        transaction: t
                    });
                    await optionRecord.update(newValue, {transaction: t});
                }
                // 更新 bones 记录
                await dataOV.update(restQuery, {transaction: t});
                return "更新成功";
            });
        } catch (error) {
            ctx.body = new ErrorModel(error);
        }
    }
}
module.exports = {
    allList,
    newData,
    revise,
    destroy
}
